import NodeCache from "node-cache";
import jwt from "jsonwebtoken";
// 默认10分钟任务超时 30s检测一次
export const taskCache: NodeCache = new NodeCache({ stdTTL: 60 * 10, checkperiod: 30 });
// 默认10分钟数据缓存 10s检测一次
export const dataCache: NodeCache = new NodeCache({ stdTTL: 60 * 10, checkperiod: 10 });

/**
 * 获取缓存数据
 * @param key
 * @returns
 */
export function getCacheData(key: string) {
	const value = dataCache.get(key);
	try {
		return JSON.parse(value + '');
	} catch (error) {
		return value;
	}
}

/**
 * 获取所有的缓存Key
 * @returns
 */
export function getTaskKeys() {
	return taskCache.keys();
}

/**
 * 解析对象
 * @param value
 * @returns
 */
export function parseObject(value: string) {
	try {
		return JSON.parse(value);
	} catch (error) {
		return value;
	}
}

taskCache.on("del", function (key: string, value: any) {
	const reject = value?.reject;
	if (reject) {
		reject(new Error(`任务${key}:超时`));
	}
});

/**
 * 获取缓存的任务
 * @param task_id
 * @returns
 */
export function getCacheTask(task_id: string): any {
	return taskCache.get(task_id);
}

/**
 * 创建一个缓存的任务
 * @param param0
 * @returns
 */
export function createCacheTask({ task_id, task_timeout }: { task_id: string; task_timeout: number }): Promise<any> {
	return new Promise((resolve, reject) => {
		taskCache.set(task_id, { resolve, reject }, task_timeout);
	});
}

/**
 * 校验JWT Token
 * @param param0
 */
export function checkJWTToken({ secretKey = '', token = ''}) {
	return jwt.verify(token?.replace('Bearer ', ''), secretKey);
}
